import * as types from './mutation-types'
import * as consts from '../util/const'

export default {
  // 用户登录，记录用户信息
  [types.USER_LOGIN] (state, payload) {
    state.isLogin = true
    state.token = payload.token
    state.userInfo = payload.userInfo
    if (payload.openId) {
      state.openId = payload.openId
    }
  },
  [types.SET_USER_INFO] (state, payload) {
    state.userInfo = payload.userInfo
  },
  [types.SET_OPEN_ID] (state, payload) {
    state.openId = payload.openId
    state.token = payload.token
  },
  [types.UPDATE_USER_INFO] (state, payload) {
    state.userInfo = payload.userInfo
  },
  [types.WITHDRAW] (state, payload) {
    if (payload.amount <= state.userInfo.balance) {
      state.userInfo.balance = state.userInfo.balance - payload.amount
    }
  },
  [types.BALANCE_PAY] (state, payload) {
    state.userInfo.balance = state.userInfo.balance - payload.amount
    if (state.userInfo.balance < 0) {
      state.userInfo.balance = 0
    }
  },
  [types.USER_LOGOUT] (state) {
    state.userInfo = {}
    state.isLogin = false
    state.token = ''
  },

  // 问题
  [types.QUESTION_RELEASE] (state, payload) {
  },

  // 分类
  [types.GET_CATALOGS] (state, payload) {
    if (payload.type == consts.CATALOG_TYPE_QUESTION) {
      state.questionCatalogs = payload.catalogs
    } else if (payload.type == consts.CATALOG_TYPE_MASTER) {
      state.masterCatalogs = payload.catalogs
    } else if (payload.type == consts.CATALOG_TYPE_PAINTING) {
      state.paintingCatalogs = payload.catalogs
    } else if (payload.type == consts.CATALOG_TYPE_NEWS) {
      state.newsCatalogs = payload.catalogs
    }
  },

  [types.GET_MASTER_LEVELS] (state, payload) {
    state.masterLevels = payload.levels
  },

  // 回答
  [types.SET_QUESTION_ANSWER] (state, payload) {
    // 判断是否存在以后的回答，如果有的话，替换，否则插入answers列表
    var answer = payload.answer
    for (var i=0; i < state.answers.length; i++) {
      var item = state.answers[i]
      if (item.question == answer.question) {
        state.answers.splice(i, 1, answer)
        return
      }
    }
    state.answers.push(answer)
  },

  [types.REMOVE_QUESTION_ANSWER] (state, payload) {
    var answer = payload.answer
    for (var i=0; i < state.answers.length; i++) {
      var item = state.answers[i]
      if (item.question == answer.question) {
        state.answers.splice(i, 1)
        return
      }
    }
  },

  [types.SAVE_LOCAL_ANSWER] (state, payload) {
    var answer = payload.answer
    state.localAnswers.push(answer)
  },
  
}
